﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Configuration;
using System.IO;
using System.Web;

namespace AxeFrog.Web
{
	/// <summary>
	/// Provides static access to standard "constant" values, mostly from the web.config file.
	/// </summary>
	public static partial class WebsiteSettings
	{
		private static string _websiteURL;

		public static string Copyright
		{
			get { return ConfigurationManager.AppSettings["Copyright"]; }
		}

		public static string DefaultCompanyLogoSrc
		{
			get { return ConfigurationManager.AppSettings["DefaultCompanyLogoSrc"]; }
		}

		public static string DefaultCompanyName
		{
			get { return ConfigurationManager.AppSettings["DefaultCompanyName"]; }
		}

		public static string SupportEmailName
		{
			get { return ConfigurationManager.AppSettings["SupportEmailName"]; }
		}

		public static string SupportEmailAddress
		{
			get { return ConfigurationManager.AppSettings["SupportEmailAddress"]; }
		}

		public static bool AllowLimitedNonActivatedLogin
		{
			get { return (ConfigurationManager.AppSettings["AllowLimitedNonActivatedLogin"] ?? "").ToBool(); }
		}

		public static string CurrencySymbol
		{
			get { return ConfigurationManager.AppSettings["CurrencySymbol"] ?? "$"; }
		}

		public static bool AllowUsersToHaveTheSameName
		{
			get { return (ConfigurationManager.AppSettings["AllowUsersToHaveTheSameName"] ?? "").ToBool(); }
		}

		public static string SaltKey
		{
			get { return ConfigurationManager.AppSettings["SaltKey"]; }
		}

		private static string ConnectionStringKey { get; set; }

		[Export("ConnectionString")]
		public static string ConnectionString
		{
			get
			{
				if(ConnectionStringKey == null)
				{
					var path = HttpContext.Current.Server.MapPath("~/App_Data/ConnectionStringKey.txt");
					ConnectionStringKey = File.Exists(path) ? File.ReadAllText(path) : "ConnectionString";
				}
				try
				{
					var cs = ConfigurationManager.ConnectionStrings[ConnectionStringKey];
					return cs.ConnectionString;
				}
				catch
				{
					throw new Exception("There is no connection string with the name \"" + ConnectionStringKey + "\". Check the file ConnectionStringKey.txt; it should be a simple text file containing the name of the connection string to be used in the web.config file.");
				}
			}
		}

		[Export("ConnectionStrings")]
		public static Dictionary<string, string> ConnectionStrings
		{
			get
			{
				if(HttpContext.Current == null)
					return null;
				var csmap = HttpContext.Current.Items["DictionaryConnectionContext.ConnectionStrings"] as Dictionary<string, string>;
				if(csmap == null)
				{
					csmap = new Dictionary<string, string>();
					foreach(ConnectionStringSettings cs in ConfigurationManager.ConnectionStrings)
						csmap.Add(cs.Name, cs.ConnectionString);
					HttpContext.Current.Items.Add("DictionaryConnectionContext.ConnectionStrings", csmap);
				}
				return csmap;
			}
		}

		[Export("ConnectionProviderName")]
		public static string ConnectionProviderName
		{
			get { return HttpContext.Current == null ? null : ConfigurationManager.AppSettings["ConnectionProviderName"]; }
		}

		[Export("PrivateKey")]
		public static string PrivateKey
		{
			get { return ConfigurationManager.AppSettings["PrivateKey"]; }
		}

		[Export("PublicKey")]
		public static string PublicKey
		{
			get { return ConfigurationManager.AppSettings["PublicKey"]; }
		}

		public static string WebsiteURL
		{
			get
			{
				if(_websiteURL == null)
				{
					var c = HttpContext.Current;
					_websiteURL = new Uri(c.Request.Url, c.Request.ApplicationPath).ToString().Trim('/');
				}
				return _websiteURL;
			}
		}

		public static string MailServerHost
		{
			get { return ConfigurationManager.AppSettings["MailServerHost"]; }
		}

		public static int MailServerPort
		{
			get { int n; return int.TryParse(ConfigurationManager.AppSettings["MailServerPort"] ?? "25", out n) ? n : 25; }
		}

		public static string MailServerUsername
		{
			get { return ConfigurationManager.AppSettings["MailServerUsername"]; }
		}

		public static string MailServerPassword
		{
			get { return ConfigurationManager.AppSettings["MailServerPassword"]; }
		}

		public static string GetEmailTemplate(string templateAppSettingsKey)
		{
			string path = ConfigurationManager.AppSettings[templateAppSettingsKey];
			if(path == null)
				throw new Exception("The appSettings key \"" + templateAppSettingsKey + "\" does not exist in the configuration file");
			path = HttpContext.Current.Server.MapPath(path);
			if(!File.Exists(path))
				throw new FileNotFoundException("The email template was not found", path);
			return File.ReadAllText(path);
		}

		public static string GetEmailTemplate(EmailTemplate template)
		{
			return File.ReadAllText(GetEmailTemplatePath(template));
		}

		public static string GetEmailTemplatePath(EmailTemplate template)
		{
			string filename;

			switch(template)
			{
				case EmailTemplate.ActivateYourAccount: filename = "email_activate.txt"; break;
				case EmailTemplate.PasswordReminder: filename = "email_password.txt"; break;
				case EmailTemplate.Welcome: filename = "email_welcome.txt"; break;
				default: throw new ArgumentException("Unexpected EmailTemplate value", "template");
			}

			return HttpContext.Current.Server.MapPath("~/App_Data/" + filename);
		}

	}

	public enum EmailTemplate
	{
		ActivateYourAccount,
		PasswordReminder,
		Welcome
	}
}